package com.csyf.manager.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.csyf.manager.channel.base.BalanceEnum;
import com.csyf.manager.channel.base.ServiceEnum;
import com.csyf.manager.dao.BalanceDto;
import com.csyf.manager.dao.SysAgentBalanceDao;
import com.csyf.manager.dao.SysPayMentDao;
import com.csyf.manager.dao.SysTradeDao;
import com.csyf.manager.entity.*;
import com.csyf.manager.exception.ApiValidateException;
import com.csyf.manager.service.SysAgentService;
import com.csyf.manager.service.SysChannelAttrBiz;
import com.csyf.manager.service.SysChannelBiz;
import com.csyf.manager.service.SysMerchBiz;
import com.csyf.manager.utils.DateHelper;
import com.csyf.manager.utils.NumberHelpler;
import com.csyf.manager.utils.page.JqGridVo;
import com.csyf.manager.utils.page.PageUtils;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: Enzo
 * @Date: 2018/4/6 17:35
 */

@Slf4j
@Service
public class SysAgentBalanceBiz {


    @Autowired
    private SysPayMentDao sysPayMentDao;

    @Autowired
    private SysAgentBalanceDao sysAgentBalanceDao;

    @Autowired
    private SysTradeDao sysTradeDao;

    @Autowired
    private SysChannelBiz sysChannelBiz;

    @Autowired
    private SysChannelAttrBiz sysChannelAttrBiz;

    @Autowired
    private SysMerchBiz sysMerchBiz;


    /**
     * @param day
     * @param channelname    sys_agent_channel--> channel_no
     * @param balanceService
     * @param tradesService
     * @param dfServices
     */
    private void querycommentmoney(int day, String channelname, String balanceService, String[] tradesService, String[] dfServices, String clearCycle) {
        //昨天日期
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, -day);
        String format = new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime());
        //前天日期
        instance.add(Calendar.DATE, -1);
        String format2 = new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime());

        Map<String, String> agentChannelMap = sysChannelBiz.queryAgentsByService(channelname);
        Set<Map.Entry<String, String>> entries = agentChannelMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            try {
                // 新增代理商昨日余额记录
                Long agentid = Long.parseLong(entry.getKey());
                String mch_id = entry.getValue();
                SysAgentBalance sysAgentBalance = new SysAgentBalance();
                sysAgentBalance.setAgentId(agentid);
                sysAgentBalance.setCurdate(format);
                sysAgentBalance.setService(balanceService);
                sysAgentBalance.setMchId(mch_id);

                sysAgentBalanceDao.insertSelective(sysAgentBalance);

                //计算昨日代理商总收益、总支出、未清算金额
                SysAgentBalance record = new SysAgentBalance();
                record.setAgentId(agentid);
                record.setCurdate(format2);
                record.setService(balanceService);
                SysAgentBalance balance = sysAgentBalanceDao.selectOne(record);
                BigDecimal yesdate = BigDecimal.ZERO;
                BigDecimal unclearing = BigDecimal.ZERO;

                if (null != balance && null != balance.getTotalmoney()) {
                    yesdate = balance.getTotalmoney();
                }

                if (null != unclearing && null != balance && null != balance.getUnclearmoney()) {
                    unclearing = balance.getUnclearmoney();
                }

                //交易收益
                String tradeServices = paseservice(tradesService);
                BigDecimal totalProfit = sysTradeDao.sumtotalProfitByServices(mch_id, format, tradeServices);

                //代付总金额
                String dfServiceStr = paseservice(dfServices);
                BalanceCount totalMap = sysPayMentDao.sumCaseOutByServices(mch_id, format, dfServiceStr);
                BigDecimal totalOut = totalMap.getPaymoney();
                BigDecimal dzOut = BigDecimal.ZERO;

                //余额代付金额
                BalanceCount balanceMap = sysPayMentDao.sumCaseOutByServices(mch_id, format, paseservice(dfServices[0]));
                BigDecimal balanceOut = balanceMap.getPaymoney();
                if (dfServices.length > 1) {
                    //垫资代付金额
                    dzOut = totalMap.getPaymoney().subtract(balanceMap.getPaymoney());
                }

                //前日未清算金额
//                SysAgentBalance unclearAgent = new SysAgentBalance();
//                unclearAgent.setAgentId(agentid);
//                unclearAgent.setCurdate(format2);
//                unclearAgent.setService(balanceService);
//                SysAgentBalance unclearBalance = sysAgentBalanceDao.selectOne(unclearAgent);
//                unclearing = unclearBalance.getUnclearmoney();

                log.info("[{}],{}代付{}总金额[{}]", format, mch_id, balanceService, totalOut);
                //总支出
                sysAgentBalance.setTotalcashout(totalOut);
                //垫资金额
                sysAgentBalance.setDzMoney(dzOut);
                //垫资笔数
                sysAgentBalance.setDzCount(totalMap.getPaycount() - balanceMap.getPaycount());
                //余额代付金额
                sysAgentBalance.setNoMoney(balanceOut);
                //余额代付笔数
                sysAgentBalance.setNoCount(balanceMap.getPaycount());
                sysAgentBalance.setTotalprofit(totalProfit);


                if ("D0".equals(clearCycle)) {
                    BigDecimal unclearingMoney = totalProfit.subtract(dzOut).add(unclearing);
                    sysAgentBalance.setTotalmoney(yesdate.subtract(balanceOut).add(unclearingMoney));
                    sysAgentBalance.setUnclearmoney(BigDecimal.ZERO);
                } else if ("T1".equals(clearCycle)) {
                    sysAgentBalance.setTotalmoney(yesdate.subtract(balanceOut));
                    sysAgentBalance.setUnclearmoney(totalProfit.subtract(dzOut).add(unclearing));
                }

                sysAgentBalanceDao.updateByPrimaryKeySelective(sysAgentBalance);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }


    private String paseservice(String... services) {
        String join = StringUtils.join(services, "','");
        String wrap = StringUtils.wrap(join, "'");
        return wrap;
    }


    /**
     * 查询通道可用余额
     *
     * @param mch_id             商户号
     * @param balanceServiceName sys_agent_balance service name
     * @param dftype             余额代付的类型
     * @return
     */
    public BigDecimal queryAvailableBalance(String mch_id, String balanceServiceName, String[] dftype) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, -1);
        String format2 = new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime());
        String format3 = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        SysAgentBalance record = new SysAgentBalance();
        record.setMchId(mch_id);
        record.setCurdate(format2);
        record.setService(balanceServiceName);
        SysAgentBalance balance = sysAgentBalanceDao.selectOne(record);
        BigDecimal yesdate = BigDecimal.ZERO;

        //凌晨0-2点间，查询可用余额
        if (null == balance || null == balance.getTotalmoney()) {
            String BEGIN_TIME = "00:00";
            String END_TIME = "02:00";
            if (DateHelper.isBelong(BEGIN_TIME, END_TIME)) {
                instance.add(Calendar.DATE, -1);
                String format4 = new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime());
                record.setCurdate(format4);
                balance = sysAgentBalanceDao.selectOne(record);

                if( null == balance){
                    SysMerchant sysAgent = sysMerchBiz.queryAgentByMerchantNo(record.getMchId());
                    record.setAgentId(sysAgent.getId());
                    sysAgentBalanceDao.insertSelective(record);
                    balance = sysAgentBalanceDao.selectOne(record);
                }

                //查询昨天代付的金额
                BigDecimal yesterdayDfMoney = sysPayMentDao.queryDfMoneyByService(mch_id, format2, paseservice(dftype));
                //查询今天代付的金额
                BigDecimal todayDfMoney = sysPayMentDao.queryDfMoneyByService(mch_id, format3, paseservice(dftype));
                //查询代付中的金额
                BigDecimal beforeDfingMoney = sysPayMentDao.queryDfingMoneyByService(mch_id, paseservice(dftype));

                List<SysChannelAttr> tradeByBalanceName = sysChannelAttrBiz.findTradeByBalanceName(balanceServiceName);
                String[] strings = new String[tradeByBalanceName.size()];
                for (int i = 0; i < tradeByBalanceName.size(); i++) {
                    strings[i] = tradeByBalanceName.get(i).getService();
                }
                BigDecimal totalProfit = sysTradeDao.sumtotalProfitByServices(mch_id, format2, paseservice(strings));

                SysChannelAttr dzServiceByBalanceName = sysChannelAttrBiz.findDZServiceByBalanceName(balanceServiceName);
                BigDecimal yes_dz_money = BigDecimal.ZERO;
                if(null != dzServiceByBalanceName){
                    String service = dzServiceByBalanceName.getService();
                    String[] aa = {service};
                    yes_dz_money = sysPayMentDao.queryDfMoneyByService(mch_id, format2, paseservice(aa));
                }

                log.info("{},{},{},{},{}",balance.getTotalmoney(),yesterdayDfMoney,todayDfMoney,totalProfit,yes_dz_money);
                //可用余额 = 前天的可用余额-昨天代付金额-今天代付金额+ 昨日收益
                yesdate = balance.getTotalmoney().subtract(yesterdayDfMoney).subtract(todayDfMoney).add(totalProfit).subtract(yes_dz_money).subtract(beforeDfingMoney);
            }
        } else {
            yesdate = balance.getTotalmoney();
            //代付中的金额+代付成功金额
            BigDecimal beforeDfingMoney = sysPayMentDao.queryDfingMoneyByService(mch_id, paseservice(dftype));
            BigDecimal todayDfMoney = sysPayMentDao.queryDfMoneyByService(mch_id, format3, paseservice(dftype));
            yesdate = yesdate.subtract(todayDfMoney).subtract(beforeDfingMoney);
        }
        return yesdate;
    }


    /**
     * 今日垫资剩余的钱
     *
     * @param mch_id       商户号
     * @param tradeService 交易的类型
     * @param dfServices   今日的代付类型
     * @param rate         可垫资的比例  0.5
     * @return
     */
    public BigDecimal queryTodayProfit(String mch_id, String[] tradeService, String[] dfServices, String rate) {
        Calendar instance = Calendar.getInstance();
        String format2 = new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime());
        String begintime = new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(instance.getTime());
        String endtime = new SimpleDateFormat("yyyy-MM-dd 23:59:59").format(instance.getTime());

        List<String> strings = Arrays.asList(dfServices);
//        if (strings.contains(ServiceEnum.XFZF_DF_DZ.toString())) {
//            begintime = new SimpleDateFormat("yyyy-MM-dd 08:00:00").format(instance.getTime());
//            endtime = new SimpleDateFormat("yyyy-MM-dd 21:59:59").format(instance.getTime());
//        }

        BigDecimal bigDecimal1 = sysTradeDao.sumtotalProfitByServicesAndBetweenTime(mch_id, paseservice(tradeService), begintime, endtime);
        log.info("[{}] 在{} 和 {} 时间段的收益 {} ", mch_id, begintime, endtime, bigDecimal1);
        bigDecimal1 = bigDecimal1.multiply(new BigDecimal(rate));

        BigDecimal bigDecimal = sysPayMentDao.queryDfMoneyByService(mch_id, format2, paseservice(dfServices));
        log.info("[{}] 已代付金额 {} ", mch_id, bigDecimal);

        BigDecimal bigDecimal2 = sysPayMentDao.queryDfingMoneyByService(mch_id, paseservice(dfServices));
        log.info("[{}] 代付中金额 {} ", mch_id, bigDecimal);

        BigDecimal money = bigDecimal1.subtract(bigDecimal).subtract(bigDecimal2).setScale(2, BigDecimal.ROUND_HALF_UP);
        log.info("[{}] 剩余金额 {} ", mch_id, money);
        return money;
    }


    /**
     * 查询今日总的交易量
     *
     * @param mch_id
     * @param tradeService
     * @return
     */
    public BigDecimal queryTodaySumTrade(String mch_id, String[] tradeService) {
        Calendar instance = Calendar.getInstance();
        String format2 = new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime());

        BigDecimal bigDecimal1 = sysTradeDao.sumtotalTradeByServices(mch_id, format2, paseservice(tradeService));
        return bigDecimal1;
    }


    /**
     * 通过service 查询当前交易的余额
     *
     * @param mchId
     * @param service
     * @return
     */
    public BigDecimal queryBalance(String mchId, String service) {
        SysChannelAttr tradeByService = sysChannelAttrBiz.findTradeByService(service);
        if (null == tradeByService) {
            return BigDecimal.ZERO;
        }

        SysChannelAttr noServiceByBalanceName = sysChannelAttrBiz.findNoServiceByBalanceName(tradeByService.getBalanceName());
        return queryAvailableBalance(mchId, tradeByService.getBalanceName(), new String[]{noServiceByBalanceName.getService()});

    }


    /**
     * 通过service 查询当前垫资交易的余额
     *
     * @param mchId
     * @param service
     * @return
     */
    public BigDecimal queryDzBalance(String mchId, String service) {
        SysChannelAttr tradeByService = sysChannelAttrBiz.findTradeByService(service);
        if (null == tradeByService) {
            return BigDecimal.ZERO;
        }
        List<SysChannelAttr> tradeByBalanceName = sysChannelAttrBiz.findTradeByBalanceName(tradeByService.getBalanceName());
        String[] strings = new String[tradeByBalanceName.size()];
        for (int i = 0; i < tradeByBalanceName.size(); i++) {
            strings[i] = tradeByBalanceName.get(i).getService();
        }

        SysChannelAttr dzServiceByBalanceName = sysChannelAttrBiz.findDZServiceByBalanceName(tradeByService.getBalanceName());
        return queryTodayProfit(mchId, strings, new String[]{dzServiceByBalanceName.getService()}, dzServiceByBalanceName.getRate().toString());
    }


    public void queryBasedfMoney(int day) {

        List<String> strings = sysChannelAttrBiz.queryAllBalanceName();
        for (String balanceName : strings) {
            List<SysChannelAttr> tradeByBalanceName = sysChannelAttrBiz.findTradeByBalanceName(balanceName);

            List<String> strings1 = new ArrayList<>();
            for (SysChannelAttr sysChannelAttr : tradeByBalanceName) {
                strings1.add(sysChannelAttr.getService());
            }

            String[] payservices = new String[strings1.size()];
            strings1.toArray(payservices);


            //String[] dfservices = {};
            String[] dfservices = new String[3];
            SysChannelAttr noServiceByBalanceName = sysChannelAttrBiz.findNoServiceByBalanceName(balanceName);

            if (null != noServiceByBalanceName) {
                dfservices[0] = noServiceByBalanceName.getService();

                SysChannelAttr dzServiceByBalanceName = sysChannelAttrBiz.findDZServiceByBalanceName(balanceName);
                if (null != dzServiceByBalanceName) {
                    dfservices[1] = dzServiceByBalanceName.getService();
                }
            }
            querycommentmoney(day, "xxxxx", balanceName, payservices, dfservices, tradeByBalanceName.get(0).getSettle());
        }


    }


    /**
     * 更新用户的账户总金额
     *
     * @param day
     */
    public void updateTotalMoney(int day) {

        //昨天日期
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, -day);
        String format = new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime());
        instance.add(Calendar.DATE, 1);
        if (validateweekend(instance)) {
            log.info("{} is weekend , not pay money do.", new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime()));
            return;
        }

        //更新账户总金额
        SysAgentBalance queryVo = new SysAgentBalance();
        queryVo.setCurdate(format);
        List<SysAgentBalance> balanceList = sysAgentBalanceDao.select(queryVo);
        log.info("更新用户账户余额总条数{}", balanceList.size());

        for (SysAgentBalance temp : balanceList) {
            SysAgentBalance agentBalance = new SysAgentBalance();
            agentBalance.setAgentId(temp.getAgentId());
            agentBalance.setCurdate(format);
            agentBalance.setService(temp.getService());
            agentBalance.setMchId(temp.getMchId());
            agentBalance.setTotalmoney(temp.getTotalmoney().add(temp.getUnclearmoney()));
            agentBalance.setUnclearmoney(BigDecimal.ZERO);
            sysAgentBalanceDao.updateByPrimaryKeySelective(agentBalance);
            log.info("update ..");
        }


    }

    /**
     * 冻结商户的账户总金额
     *
     * @param agentId
     * @param serviceType
     * @param mchFreezeFee
     */
    public void updateMchTotalMoney(Long agentId, String serviceType, BigDecimal mchFreezeFee) throws Exception {
        int day = 1;
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, -day);
        String format = new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime());

        SysAgentBalance vo = new SysAgentBalance();
        vo.setCurdate(format);
        vo.setAgentId(agentId);
        vo.setService(serviceType);

        List<SysAgentBalance> balanceList = sysAgentBalanceDao.select(vo);
        if (null == balanceList || balanceList.isEmpty()) {
            throw new ApiValidateException("商户当前余额不存在，请联系技术！");
        }
        SysAgentBalance sysAgentBalance = balanceList.get(0);

        SysAgentBalance temp = new SysAgentBalance();
        temp.setAgentId(sysAgentBalance.getAgentId());
        temp.setCurdate(format);
        temp.setService(sysAgentBalance.getService());
        temp.setMchId(sysAgentBalance.getMchId());
        temp.setTotalmoney(sysAgentBalance.getTotalmoney().subtract(mchFreezeFee));
        temp.setFrozen(sysAgentBalance.getFrozen().add(mchFreezeFee));
        sysAgentBalanceDao.updateByPrimaryKeySelective(temp);
    }

    /**
     * 查询当前未清算余额
     *
     * @param merchantNo
     * @return
     */
    public BigDecimal queryUnclearBalance(String merchantNo, String service) {

        BigDecimal unclearmoney = BigDecimal.ZERO;

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, -1);
        String format2 = new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime());
        SysAgentBalance record = new SysAgentBalance();
        record.setMchId(merchantNo);
        record.setCurdate(format2);
        record.setService(service);
        SysAgentBalance balance = sysAgentBalanceDao.selectOne(record);

        if (null != balance) {
            unclearmoney = balance.getUnclearmoney();
        }
        return unclearmoney;

    }


    /**
     * 判断是否是周末
     *
     * @param calendar
     * @return
     */
    private boolean validateweekend(Calendar calendar) {
        //判断日期是否是周六周日
        if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ||
                calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
            return true;
        }
        return false;
    }

    public JqGridVo queryOrderByUserId(SysAgentBalance vo, Integer page, Integer rows) {

        PageHelper.startPage(page, rows);
        PageHelper.orderBy("curdate desc");


        Example example = new Example(SysAgentBalance.class);
        Example.Criteria criteria = example.createCriteria();
        PageUtils.andEqualTo(criteria, "agentId", vo.getAgentId());
        PageUtils.andEqualTo(criteria, "mchId", vo.getMchId());
        PageUtils.andEqualTo(criteria, "service", vo.getService());
        PageUtils.andEqualTo(criteria, "curdate", vo.getCurdate());
        List<SysAgentBalance> select = sysAgentBalanceDao.selectByExample(example);

        //自定义数据列
        JqGridVo jqGridVo = PageUtils.pasrJqGrid(select);


        if (StringUtils.isNotBlank(vo.getService())) {
            BalanceDto totalFee = sysAgentBalanceDao.queryTotalFeeByCondition(vo);
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("mchId", "总计：");
            jsonObj.put("totalmoney", totalFee.getTotalmoney());
            jsonObj.put("totalprofit", totalFee.getTotalprofit());
            jsonObj.put("totalcashout", totalFee.getTotalcashout());
            jsonObj.put("unclearmoney", totalFee.getUnclearmoney());
            jqGridVo.setUserdata(jsonObj);
        }
        return jqGridVo;
    }

    /**
     * 糯米支付
     * @param day
     */
    public void queryNMChannnelData(int day) {
        String[] payservices = new String[]{ServiceEnum.NM_ALI_H5.toString()};
        String[] dfservices = new String[]{ServiceEnum.NM_ALI_DF_NO.toString(), ServiceEnum.NM_ALI_DF_DZ.toString()};

        querycommentmoney(day, "nmpay", BalanceEnum.NM_PAY.toString(), payservices, dfservices, "D0");
    }

    /**
     * 小机 支付宝
     */
    public void queryXiaojiChannelData(int day) {
        String[] payservices = new String[]{ServiceEnum.XJ_ALI_SM.toString()};
        String[] dfservices = new String[]{ServiceEnum.XJ_ALI_DF_NO.toString(), ServiceEnum.XJ_ALI_DF_DZ.toString()};

        querycommentmoney(day, "xjpay", BalanceEnum.XJ_PAY.toString(), payservices, dfservices, "D0");
    }

    /**
     * 统计拼多多 支付宝
     * @param day
     */
    public void queryPingduoduoAliChannelData(int day) {
        String[] payservices = new String[]{ServiceEnum.PDD_ALI_SM.toString()};
        String[] dfservices = new String[]{ServiceEnum.PDD_ALI_DF_NO.toString(), ServiceEnum.PDD_ALI_DF_DZ.toString()};

        querycommentmoney(day, "pdd_alipay", BalanceEnum.PDD_ALIPAY.toString(), payservices, dfservices, "D0");
    }

    /**
     * 统计拼多多 微信
     * @param day
     */
    public void queryPingduoduoWxChannelData(int day) {
        String[] payservices = new String[]{ServiceEnum.PDD_WX_SM.toString()};
        String[] dfservices = new String[]{ServiceEnum.PDD_WX_DF_NO.toString(), ServiceEnum.PDD_WX_DF_DZ.toString()};

        querycommentmoney(day, "pdd_wxpay", BalanceEnum.PDD_WXPAY.toString(), payservices, dfservices, "D0");
    }

    /**
     * 查询D0 百分之几 当前未清算余额
     *
     * @param mch_id
     * @return
     */
    public BigDecimal querySomeUnclearBalance(String mch_id, String[] tradeService, String[] dfServices, String rate) {

        BigDecimal unclearmoney = BigDecimal.ZERO;

        Calendar instance = Calendar.getInstance();
        String format2 = new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime());
        String begintime = new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(instance.getTime());
        String endtime = new SimpleDateFormat("yyyy-MM-dd 23:59:59").format(instance.getTime());

        List<String> strings = Arrays.asList(dfServices);

        BigDecimal bigDecimal1 = sysTradeDao.sumtotalProfitByServicesAndBetweenTime(mch_id, paseservice(tradeService), begintime, endtime);
        log.info("[{}] 在{} 和 {} 时间段的收益 {} ", mch_id, begintime, endtime, bigDecimal1);

        BigDecimal subtract = NumberHelpler.subtract(BigDecimal.ONE, new BigDecimal(rate));
        bigDecimal1 = bigDecimal1.multiply(subtract);

        unclearmoney = NumberHelpler.add(unclearmoney, bigDecimal1);

        return unclearmoney;

    }

    /**
     * 查询当前通道冻结金额
     *
     * @param merchantNo
     * @return
     */
    public BigDecimal queryFrozeBalance(String merchantNo, String service) {

        BigDecimal frozenmoney = BigDecimal.ZERO;

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, -1);
        String format2 = new SimpleDateFormat("yyyy-MM-dd").format(instance.getTime());
        SysAgentBalance record = new SysAgentBalance();
        record.setMchId(merchantNo);
        record.setCurdate(format2);
        record.setService(service);
        SysAgentBalance balance = sysAgentBalanceDao.selectOne(record);

        if (null != balance) {
            frozenmoney = balance.getFrozen();
        }
        return frozenmoney;

    }
}
